<template>
	<!-- 自定义收银台页面模式 -->
	<view class="uni-pay bottom-index">
		<!-- #ifdef MP-WEIXIN -->
		<qmy-custom-navbar :title="'收银台'"></qmy-custom-navbar>
		<!-- #endif -->
		<!-- 加载中蒙版 -->
		<qmy-mask-load :dataLoaded="dataLoaded"></qmy-mask-load>
		<view class="mobile-pay-popup" v-if="insideData && insideData.currentProviders">
			<view class="mobile-pay-popup-amount-box"
				:style="{paddingTop:menuObject.top + menuObject.height +20 + 'px'}">
				<view class="fw-600">待支付金额：</view>
				<view class="mobile-pay-popup-amount fw-600">{{ (options.total_fee / 100).toFixed(2) }}</view>
			</view>

			<!-- 支付方式 -->
			<view>
				<view class="info-item">
					<view class="payment-method">
						<image
							src="https://gd-hbimg.huaban.com/da39f6332f0563d95d1d59f3523cfad9de35537d1829d-vrBQ0y_fw1200"
							mode="aspectFit"></image>
						<text class="fs-28">微信支付</text>
					</view>
					<view>
						<checkbox-group @change="checkboxChange('wxpay')">
							<label class="checkbox-box">
								<checkbox :checked="selectedPayment === 'wxpay'" activeBackgroundColor="#14cc60"
									activeBorderColor="#14cc60" style="transform: scale(0.7);" />
							</label>
						</checkbox-group>
					</view>
				</view>
				<view v-if="!versionAuditStatus" class="info-item">
					<view class="payment-method">
						<image
							src="https://gd-hbimg.huaban.com/332e7cee43ebcd885277a3e7628ec387d85b255726f4-wrmcKN_fw1200"
							mode="aspectFit"></image>
						<view class="fs-28">
							<text>余额支付</text>
							<text>(¥{{ (userBalance / 100).toFixed(2) }})</text>
							<text class="fs-26 col-00ba31 ml-10"
								@click="$NavigateTo('/qmy_user/user/myWallet')">去充值</text>
						</view>
					</view>
					<view>
						<checkbox-group @change="checkboxChange('balance')">
							<label class="checkbox-box">
								<checkbox :checked="selectedPayment === 'balance'" activeBackgroundColor="#14cc60"
									activeBorderColor="#14cc60" style="transform: scale(0.7);" />
							</label>
						</checkbox-group>
					</view>
				</view>
			</view>

			<!-- 退款政策 -->
			<view v-if="refundPolicy.length > 0" class="refund-policy">
				<view class="policy-header ">
					<text class="fs-30 fw-600">{{refundPolicy[0].title}}</text>
				</view>
				<view class="policy-content">
					<mp-html :content="refundPolicy[0].content"></mp-html>
				</view>

				<!-- 退款规则表格 -->
				<view v-if="type === 'sign-up'" class="policy-table">
					<view class="table-header">
						<view class="table-cell">申请退款时间</view>
						<view class="table-cell">退款规则</view>
					</view>
					<view class="table-row">
						<view class="table-cell">开始前24小时</view>
						<view class="table-cell">可全额退款</view>
					</view>
					<view class="table-row">
						<view class="table-cell">活动进行中</view>
						<view class="table-cell">特殊原因协商</view>
					</view>
				</view>
			</view>

			<!-- 免责声明 -->
			<view v-if="refundPolicy.length > 1" class="disclaimer h-40-vh">
				<view class="policy-header ">
					<text class="fs-30 fw-600">{{refundPolicy[1].title}}</text>
				</view>
				<view class="disclaimer-content">
					<mp-html :content="refundPolicy[1].content"></mp-html>
				</view>
			</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<!-- 底部定位发布按钮 -->
		<view @click="createOrder()" class="w-100 fixed-bottom bac-col-00b">
			<view class="w-100 bg-col-00b text-ali-c">
				<view class="fs-30 col-f fw-600">确认付款 ¥{{ (options.total_fee / 100).toFixed(2) }}</view>
			</view>
		</view>
		<!-- #endif -->
		<!-- 挂载支付组件 -->
		<uni-pay ref="uniPay" :to-success-page="false" @mounted="onMounted" @success="onSuccess"></uni-pay>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// #ifdef MP-WEIXIN
				menuObject: uni.getMenuButtonBoundingClientRect(),
				// #endif
				// #ifndef MP-WEIXIN
				menuObject: 0,
				// #endif
				options: {
					total_fee: "",
				},
				insideData: {}, // uni-pay组件mounted事件获得的数据
				adpid: "", // 广告id
				return_url: "", // 支付成功后点击查看订单跳转的订单详情页面地址
				main_color: "", // 支付成功页面的主色调
				refundPolicy: [], // 退款政策
				dataLoaded: false, // 数据加载状态
				selectedPayment: 'wxpay', // 默认选中微信支付
				userBalance: 0, // 用户当前余额
				type: 'sign-up', // 订单类型
				versionAuditStatus: true
			}
		},
		// 监听 - 页面每次【加载时】执行(如：前进)
		onLoad(options = {}) {
			if (options.options) {
				options = JSON.parse(decodeURI(options.options));
				if (options.type === 'goods') {
					this.type = 'goods';
				}
				this.options = options;
			}
			// 获取退款政策和免责声明
			this.getRefundPolicy();
			this.getVersionAuditStatus();
		},
		onShow() {
			// 获取用户当前余额
			this.getUserBalance();
		},
		// 函数 
		methods: {
			// 查询版本
			getVersionAuditStatus() {
				this.$Route('get-public-data', true).getVersionAuditStatus().then((res) => {
					this.versionAuditStatus = res.data[0].status;
				})
			},
			// 获取退款政策和免责声明
			getRefundPolicy() {
				this.$Route('get-public-data', true).getRefundPolicy(this.type === 'sign-up' ? '67dbf17db9fb2371a7db87c0' :
					'67f3acdb21821bfd35b08a26').then((res) => {
					this.refundPolicy = res.data[0].articles
				}).catch((err) => {
					console.log(err)
				})
			},
			// 获取用户当前余额
			getUserBalance() {
				this.$Route('get-private-data', !this.dataLoaded).getUserBalance().then((res) => {
					this.userBalance = res.data[0].balance;
					this.dataLoaded = true;
				}).catch((err) => {
					this.dataLoaded = true;
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1600);
				})
			},
			// 监听 - 支付组件加载完毕事件
			onMounted(insideData) {
				this.insideData = insideData;
			},
			// 发起支付
			createOrder() {
				this.$debounce(() => {
					if (this.selectedPayment === 'balance' && this.options.type === 'sign-up') {
						this.$Route('add-private-data').paySignUpOrder(this.options).then((res) => {
							this.$Toast(res.msg)
							setTimeout(() => {
								this.$NavigateBack()
							}, 1000)
						}).catch((err) => {
							console.error('遇到错误:', err); // 打印错误信息
							let {
								code,
								msg
							} = this.$parseError(err); // 调用公共解析方法
							this.$Toast(msg);
							setTimeout(() => {
								if (code === 401) {
									this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
								}
							}, 1600);
						})
					} else if (this.selectedPayment === 'balance' && this.options.type === 'goods') {
						// 余额支付商品订单
						this.$Route('add-private-data').payGoodsOrder(this.options).then((res) => {
							this.$Toast(res.msg)
							setTimeout(() => {
								this.getOpenerEventChannel().emit('refreshData', '')
								this.$NavigateBack()
							}, 1000)
						}).catch((err) => {
							console.error('遇到错误:', err); // 打印错误信息
							let {
								code,
								msg
							} = this.$parseError(err); // 调用公共解析方法
							this.$Toast(msg);
							setTimeout(() => {
								if (code === 401) {
									this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
								}
							}, 1600);
						})
					} else if (this.selectedPayment === 'wxpay') {
						// 微信支付
						// 如果是活动订单，先校验活动状态
						if (this.options.type === 'sign-up') {
							this.$Route('add-private-data').signUpCheckActivityStatus(this.options.custom
								.activity_id).then((
								res) => {
								if (res.code === 400) {
									this.$Toast(res.msg)
									setTimeout(() => {
										this.$NavigateTo(
											'/qmy_user/user/userPersonal'); // 跳转到个人信息页面
									}, 1600)
									return;
								} else if (res.code !== 200) {
									this.$Toast(res.msg)
									return;
								}
								this.submitWxPay();
							}).catch((err) => {
								console.error('遇到错误:', err); // 打印错误信息
								let {
									code,
									msg
								} = this.$parseError(err); // 调用公共解析方法
								this.$Toast(msg);
								setTimeout(() => {
									if (code === 401) {
										this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
									}
								}, 1600);
							})
						} else {
							this.submitWxPay();
						}
					}
				}, 1000, true, "createOrder")
			},
			// 提交微信支付
			submitWxPay() {
				if (this.options.type === 'sign-up') {
					// 开始支付
					Object.assign(this.options, {
						provider: 'wxpay'
					});
					this.$refs.uniPay.createOrder(this.options);
					return;
				}
				// 查询订单状态
				this.$Route('get-private-data').getOrderStatus(this.options.out_trade_no).then((res) => {
					if (res.data === 1) {
						this.$Toast('订单已支付');
						return;
					} else {
						// 开始支付
						Object.assign(this.options, {
							provider: 'wxpay'
						});
						this.$refs.uniPay.createOrder(this.options);
					}
				}).catch((err) => {
					console.error('遇到错误:', err); // 打印错误信息
					let {
						code,
						msg
					} = this.$parseError(err); // 调用公共解析方法
					this.$Toast(msg);
					setTimeout(() => {
						if (code === 401) {
							this.$NavigateTo('/qmy_user/login'); // 跳转到登录页面
						}
					}, 1600);
				})
			},
			// 监听事件 - 支付成功
			onSuccess(res) {
				if (res.user_order_success) {
					// 代表用户已付款，且你自己写的回调成功并正确执行了
					uni.redirectTo({
						url: `/uni_modules/uni-pay/pages/success/success?out_trade_no=${res.out_trade_no}&order_no=${res.pay_order.order_no}&pay_date=${res.pay_order.pay_date}&total_fee=${res.pay_order.total_fee}&adpid=${this.adpid}&return_url=${this.return_url}&main_color=${this.main_color}`
					})
				} else {
					// 代表用户已付款，但你自己写的回调执行失败（通常是因为你的回调代码有问题）
					if (this.type === 'sign-up') {
						this.$Toast('报名失败，请联系客服退款')
					} else {
						this.$Toast('支付失败，请联系客服退款')
					}
				}
			},
			// 选择支付方式
			selectPayment(type) {
				this.selectedPayment = type;
			},
			// 复选框变化处理
			checkboxChange(type) {
				this.selectedPayment = type;
			},
		}
	}
</script>
<style lang="scss" scoped>
	.mobile-pay-popup {
		min-height: calc(100vh - var(--window-bottom) - var(--window-top));
		background-color: #f3f3f3;
		border-radius: 30rpx 30rpx 0 0;
		overflow: hidden;

		.mobile-pay-popup-title {
			background-color: #ffffff;
			text-align: center;
			font-weight: bold;
			font-size: 40rpx;
			padding: 20rpx;
		}

		.mobile-pay-popup-amount-box {
			background-color: #ffffff;
			padding: 30rpx;

			.mobile-pay-popup-amount {
				color: #ee3939;
				font-size: 60rpx;
				margin-top: 20rpx;
			}
		}

		.mobile-pay-popup-provider-list {
			background-color: #ffffff;
			margin-top: 20rpx;
		}
	}

	/* 信息项样式 */
	.info-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-color: #ffffff;
		margin-bottom: 2rpx;
		margin-top: 2rpx;
	}

	.info-label {
		font-weight: 600;
		font-size: 30rpx;
		color: #333;
	}

	.info-value {
		font-size: 30rpx;
		color: #333;
	}

	.price {
		color: #ff4d4f;
		font-weight: 500;
	}

	/* 票数选择样式 */
	.ticket-selection {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		background-color: #ffffff;
		margin-bottom: 20rpx;
	}

	.ticket-group {
		font-size: 30rpx;
		color: #333;
	}

	.ticket-counter {
		display: flex;
		align-items: center;
	}

	.counter-btn {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border: 1px solid #e0e0e0;
		font-size: 36rpx;
	}

	.counter-number {
		width: 80rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-top: 1px solid #e0e0e0;
		border-bottom: 1px solid #e0e0e0;
	}

	/* 支付方式样式 */
	.payment-method {
		display: flex;
		align-items: center;
	}

	.payment-method image {
		width: 40rpx;
		height: 40rpx;
		margin-right: 10rpx;
	}

	/* 退款政策样式 */
	.refund-policy {
		background-color: #ffffff;
		padding: 30rpx;
	}

	.policy-header,
	.disclaimer-header {
		display: flex;
		align-items: center;
		margin-bottom: 20rpx;
		font-size: 30rpx;
		font-weight: 500;
	}

	.policy-icon,
	.disclaimer-icon {
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background-color: #e6f7ff;
		display: flex;
		justify-content: center;
		align-items: center;
		margin-right: 10rpx;
	}

	.policy-icon .iconfont {
		color: #1890ff;
		font-size: 24rpx;
	}

	.disclaimer-icon .iconfont {
		color: #faad14;
		font-size: 24rpx;
	}

	.policy-content {
		font-size: 26rpx;
		margin-bottom: 20rpx;
	}

	/* 退款规则表格 */
	.policy-table {
		border: 1px solid #e0e0e0;
		border-radius: 8rpx;
		overflow: hidden;
	}

	.table-header,
	.table-row {
		display: flex;
	}

	.table-header {
		background-color: #14cc60;
		color: #fff;
	}

	.table-cell {
		flex: 1;
		padding: 20rpx;
		text-align: center;
		font-size: 28rpx;
		border-right: 1px solid #e0e0e0;
		border-bottom: 1px solid #e0e0e0;
	}

	.table-cell:last-child {
		border-right: none;
	}

	.table-row:last-child .table-cell {
		border-bottom: none;
	}

	/* 免责声明样式 */
	.disclaimer {
		background-color: #ffffff;
		padding: 30rpx;
		margin-bottom: 20rpx;
		margin-top: 20rpx;
	}

	.disclaimer-content {
		font-size: 28rpx;
		line-height: 1.5;
	}

	/* 底部支付按钮 */
	.payment-btn {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background-color: #07c160;
		color: #ffffff;
		display: flex;
		justify-content: center;
		align-items: center;
		font-size: 32rpx;
		font-weight: 500;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding-top: 30rpx;
		padding-bottom: 30rpx !important;
		padding-bottom: calc(30rpx + constant(safe-area-inset-bottom)) !important;
		padding-bottom: calc(30rpx + env(safe-area-inset-bottom)) !important;
		z-index: 9;
		transition: background-color 0.2s ease;
	}

	.fixed-bottom:active {
		background-color: #11b051 !important;
		/* 点击时背景颜色变化 */
	}

	.agreement {
		color: #14cc60;
		cursor: pointer;
	}

	.checkbox-box ::v-deep .uni-checkbox-input {
		border-radius: 100%;
	}

	.checkbox-box ::v-deep .uni-checkbox-input.uni-checkbox-input-checked {
		border-color: $uni-color-primary;
		color: #FFFFFF !important;
		background-color: $uni-color-primary;
	}
</style>